﻿namespace Snipps.Infrastructure.Behaviors
{
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Interactivity;

    public class ExecCmdFromInputBindingsOnPreviewKeyDownBahavior : Behavior<FrameworkElement>
    {
        protected override void OnAttached()
        {
            AssociatedObject.PreviewKeyDown += AssociatedObject_PreviewKeyDown;
        }

        protected override void OnDetaching()
        {
            AssociatedObject.PreviewKeyDown -= AssociatedObject_PreviewKeyDown;
        }

        private void AssociatedObject_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            foreach (InputBinding inputBinding in AssociatedObject.InputBindings)
            {
                var keyGesture = inputBinding.Gesture as KeyGesture;
                if (keyGesture != null && keyGesture.Key == e.Key && keyGesture.Modifiers == Keyboard.Modifiers)
                {
                    if (inputBinding.Command != null && inputBinding.Command.CanExecute(null))
                    {
                        inputBinding.Command.Execute(null);
                        e.Handled = true;
                    }
                }
            }
        }
    }
}